package com.moon.common.criteria;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressWarnings("unchecked")
public class Expression {
	
    private Class clazz;
    private String fieldName;
    private String matchType;
    private Object value;
    
	public Object getValue() throws SecurityException, NoSuchFieldException {
		String type = null;
		if (matchType.equals("LIKE") || matchType.equals("NOTLIKE")
				|| matchType.equals("IN") || matchType.equals("NOTIN")) {
			type="String";
		}else{
			if(fieldName.indexOf(".")>-1){
				String[] dipNames = fieldName.split(".");
				for(String name:dipNames){
					type = name;
					type = clazz.getDeclaredField(type).getType().getSimpleName();
				}
			}
			type = clazz.getDeclaredField(fieldName).getType().getSimpleName();	
		}
		
		if("Long".equals(type)){
			value = Long.valueOf((String) value);
		}
		if("Integer".equals(type)){
			value = Integer.valueOf((String) value);
		}
		if("Boolean".equals(type)){
			value = Boolean.valueOf((String) value);
		}
		if("String".equals(type)){
			value = String.valueOf(value);
		}
		if("Date".equals(type)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date date = sdf.parse((String) value);
				value = date;
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if("Timestamp".equals(type)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
			try {
				Date date = sdf.parse((String) value);
				value = new Timestamp(date.getTime());
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if("Double".equals(type)){
			value = Double.parseDouble((String) value);
		}
		if("Float".equals(type)){
			value = Float.parseFloat((String) value);
		}
		return value;
	}
	
	public void setValue(Object value) {
		this.value = value;
	}
	
	public String getMatchType() {
		return matchType;
	}

	public void setMatchType(String matchType) {
		this.matchType = matchType;
	}
	
	public String getFieldName() {
		return fieldName;
	}
	
	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}
	
	public Class getClazz() {
		return clazz;
	}
	
	public void setClazz(Class clazz) {
		this.clazz = clazz;
	}
	
}
